import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { 
  Card, 
  Button, 
  Typography, 
  Descriptions, 
  Divider, 
  message, 
  Space,
  Result,
  Radio
} from 'antd';
import { CheckCircleOutlined, CreditCardOutlined, WalletOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Title, Text } = Typography;
const API_BASE_URL = 'http://localhost:8080/api';

const OrderConfirm = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [orderSuccess, setOrderSuccess] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState('creditCard');

  // 从location.state获取订单数据，如果没有则使用默认数据
  const orderData = location.state?.orderData || {
    movieTitle: '钢铁之躯',
    cinemaName: '星光影院',
    hallName: '1号厅',
    showtime: '2023-05-15 10:00:00',
    seat: '5排13座',
    ticketPrice: 35,
    serviceFee: 5,
    totalPrice: 40
  };

  const handlePayment = async () => {
    setLoading(true);

    // Simulate a successful payment process with a slight delay
    setTimeout(async () => {
      try {
        // Attempt to call backend API to create order
        const orderDTO = {
          orderNumber: `ORD${Date.now()}`,
          movieTitle: orderData.movieTitle,
          cinemaName: orderData.cinemaName,
          hallName: orderData.hallName,
          showtime: orderData.showtime,
          seats: orderData.seat,
          quantity: 1,
          ticketPrice: orderData.ticketPrice,
          serviceFee: orderData.serviceFee,
          totalPrice: orderData.totalPrice,
          status: 'PAID', // Assume PAID status on success
          paymentMethod: paymentMethod,
          userId: 1, // Placeholder: Should be actual user ID
          createdAt: new Date().toISOString()
        };
        const response = await axios.post(`${API_BASE_URL}/orders`, orderDTO);
        // Log success from backend perspective (optional)
        console.log('Order created on backend:', response.data);

      } catch (error) {
        // Log backend error, but proceed with frontend success display
        console.error('Error creating order on backend:', error);
        message.warn('订单提交后端时发生问题，但前端已显示支付成功。');
      } finally {
        // Always show success on frontend, regardless of backend call result
        setOrderSuccess(true);
        message.success('支付成功！');
        setLoading(false);
      }
    }, 1500); // Simulate network delay
  };

  if (orderSuccess) {
    return (
      <Result
        status="success"
        title="支付成功！"
        subTitle="您的订单已完成支付，可以在个人订单中查看详情"
        extra={[
          <Button 
            type="primary" 
            key="orders" 
            onClick={() => navigate('/orders')}
          >
            查看订单
          </Button>,
          <Button 
            key="movies" 
            onClick={() => navigate('/movies')}
          >
            继续购票
          </Button>,
        ]}
      />
    );
  }

  return (
    <div style={{ padding: '24px', maxWidth: '800px', margin: '0 auto' }}>
      <div>测试123</div>
      <Card>
        <Title level={2}>确认订单</Title>
        <Text type="warning">请在14:43内完成支付</Text>
        <Divider />
        
        <Title level={3}>订单信息</Title>
        <Descriptions column={1}>
          <Descriptions.Item label="电影">
            {orderData.movieTitle}
          </Descriptions.Item>
          <Descriptions.Item label="影院">
            {orderData.cinemaName}
          </Descriptions.Item>
          <Descriptions.Item label="影厅">
            {orderData.hallName}
          </Descriptions.Item>
          <Descriptions.Item label="场次">
            {orderData.showtime}
          </Descriptions.Item>
          <Descriptions.Item label="座位">
            {orderData.seat}
          </Descriptions.Item>
        </Descriptions>

        <Divider />
        
        <Title level={3}>订单摘要</Title>
        <Descriptions>
          <Descriptions.Item label="票价 (1 x ¥35)">
            ¥{orderData.ticketPrice}
          </Descriptions.Item>
          <Descriptions.Item label="服务费">
            ¥{orderData.serviceFee}
          </Descriptions.Item>
          <Descriptions.Item label="总计">
            <Text strong type="danger">¥{orderData.totalPrice}</Text>
          </Descriptions.Item>
        </Descriptions>

        <Divider />
        
        <Title level={3}>支付方式</Title>
        <Radio.Group 
          value={paymentMethod} 
          onChange={e => setPaymentMethod(e.target.value)}
          style={{ marginBottom: '24px' }}
        >
          <Space direction="vertical">
            <Radio value="creditCard">
              <Space>
                <CreditCardOutlined />
                信用卡支付
              </Space>
            </Radio>
            <Radio value="wallet">
              <Space>
                <WalletOutlined />
                电子钱包
              </Space>
            </Radio>
          </Space>
        </Radio.Group>
        
        <div style={{ textAlign: 'center', marginTop: '24px' }}>
          <Space>
            <Button onClick={() => navigate(-1)}>
              返回修改
            </Button>
            <Button 
              type="primary" 
              size="large"
              loading={loading}
              onClick={() => { alert('button clicked'); handlePayment(); }}
              icon={<CheckCircleOutlined />}
            >
              立即支付 ¥{orderData.totalPrice}
            </Button>
          </Space>
        </div>
      </Card>
    </div>
  );
};

export default OrderConfirm; 